import {getUserInfo} from '@/api/login'
import {ElNotification} from "element-plus";
import {h} from "vue";

let ws = null    // websocket实例
let lockReconnect = false; // websocket连接状态，避免重复连接
let reconnectTimer = 2000  // 断开后2s自动重连
let name = ''

function wsOpen() {
    if(process.env.NODE_ENV==='development') return
    let url = window.location.href
    if (!url.endsWith('login')) {
        getUserInfo().then((res) => {
            name = res.data.data.sysUser.username
            if (ws?.readyState === 1) return
            setWebsocket()
        })
    }

}

function setWebsocket() {
   let host= window.location.hostname
    let token = JSON.parse(sessionStorage.getItem('pig-access_token')).content
    ws = new WebSocket(`ws://${host}:9999/om/websocket/${name}?access_token=${token}`)
    ws.addEventListener('open', () => {
        console.log('服务连接成功')
    })
    ws.addEventListener('close', () => {
        console.log('服务已断开')
        reconnect()
    })
    ws.addEventListener('error', () => {
        console.log('服务发生异常')
        reconnect()
    })
    ws.addEventListener('message', event => {
        const utterance = new SpeechSynthesisUtterance();
        utterance.text = '您有一个新工单,请注意查收';
        utterance.lang = 'zh-CN';
        utterance.rate = 0.9;
        utterance.pitch = 1.5;
        speechSynthesis.speak(utterance);
        ElNotification({
            title: '消息提示',
            message: h('i', {style: 'color: teal'}, '您有一个新工单,请注意查收!'),
            duration: 0,
            offset: 100,
        })
    })
}

// 重连
function reconnect() {
    if (lockReconnect) return;
    lockReconnect = true;
    setTimeout(function () {
        wsOpen();
        lockReconnect = false;
    }, reconnectTimer);
}

// 页面关闭断开socket连接
window.onbeforeunload = function () {
    ws.close()
    return;
}

// 向外暴露
export {
    ws,
    wsOpen
}